#!/usr/bin/env python3
"""
评委打分实时显示系统启动脚本
"""

import uvicorn
import os
import sys
import subprocess
import shutil
from pathlib import Path

# 添加backend目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'backend'))

PROJECT_ROOT = Path(__file__).parent.resolve()
APP_DIR = PROJECT_ROOT / "app"
APP_DIST_DIR = APP_DIR / "dist"
STATIC_DIR = PROJECT_ROOT / "static"


def run_command(cmd, cwd):
    result = subprocess.run(cmd, cwd=cwd, shell=True)
    if result.returncode != 0:
        raise RuntimeError(f"命令执行失败: {cmd}")


def build_frontend():
    if not APP_DIR.exists():
        print("[前端] 未找到 app 目录，跳过前端构建")
        return

    print("[前端] 开始构建 Vite + Vue3 应用...")
    # 优先使用 pnpm / yarn / npm 中可用的一个
    package_manager = None
    for pm in ["pnpm", "yarn", "npm"]:
        if shutil.which(pm):
            package_manager = pm
            break

    if package_manager is None:
        raise RuntimeError("未检测到可用的包管理器 (pnpm/yarn/npm)，请安装其中之一")

    install_cmd = {
        "pnpm": "pnpm install --silent",
        "yarn": "yarn install --silent",
        "npm": "npm install --silent"
    }[package_manager]

    build_cmd = {
        "pnpm": "pnpm run build",
        "yarn": "yarn build",
        "npm": "npm run build"
    }[package_manager]

    # 安装依赖（如果 node_modules 不存在或包有变更）
    print(f"[前端] 使用 {package_manager} 安装依赖...")
    run_command(install_cmd, cwd=str(APP_DIR))

    # 构建
    print("[前端] 正在构建...")
    run_command(build_cmd, cwd=str(APP_DIR))

    if not APP_DIST_DIR.exists():
        raise RuntimeError("[前端] 构建完成后未找到 dist 目录")

    print("[前端] 构建完成")


def copy_dist_to_static():
    STATIC_DIR.mkdir(parents=True, exist_ok=True)

    # 将 dist 中的内容复制（覆盖）到 static 目录
    print("[前端] 将 dist 内容复制到 static 目录...")
    for item in APP_DIST_DIR.iterdir():
        dest = STATIC_DIR / item.name
        if item.is_dir():
            if dest.exists():
                shutil.rmtree(dest)
            shutil.copytree(item, dest)
        else:
            shutil.copy2(item, dest)
    print("[前端] 复制完成")


if __name__ == "__main__":
    print("启动评委打分实时显示系统...")
    print("访问地址:")
    print("  - 评委打分页面: http://localhost:8000/")
    print("  - 大屏显示页面: http://localhost:8000/display")
    print("  - 管理界面: http://localhost:8000/admin")
    print("\n按 Ctrl+C 停止服务")

    try:
        build_frontend()
        copy_dist_to_static()
    except Exception as e:
        print(f"[前端] 构建或复制阶段出现问题: {e}")
        print("[前端] 将跳过前端构建并直接启动后端服务（可能会使用旧的 static 内容）")

    uvicorn.run(
        "backend.main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info"
    ) 